#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#       untitled.py
#       
#       Copyright 2010 Matteo Brusa <matteo@dell-desktop>
#       
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#       
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#       
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.


import thread
import time
import rhythmdb
import random

class DBScanner():
    def __init__(self, shell):
        args=(shell, )
        thread.start_new_thread(self.start_scanner, args)   
            
    def start_scanner(self, shell):
        while (shell.props.db.is_busy()):
            time.sleep(0.5)
            print("db busy, will retry")
        self.scan(shell)
        
    def scan(self, shell):
        print "scanning"
        self.shell=shell
        
        db= shell.props.db       
        self.type_song=db.entry_type_get_by_name("song")
        
        albums_set=set()
        artists_set=set()
                
        shell.props.library_source.reset_filters()

        # import artists
        for row in shell.props.library_source.props.query_model:
            if row[0].get_entry_type()==self.type_song:
                artists_set.add(db.entry_get(row[0], rhythmdb.PROP_ARTIST))

        # import albums
        for row in shell.props.library_source.props.query_model:
            if row[0].get_entry_type()==self.type_song:
                artist= db.entry_get(row[0], rhythmdb.PROP_ARTIST)
                album= db.entry_get(row[0], rhythmdb.PROP_ALBUM)
                path= db.entry_get(row[0], rhythmdb.PROP_LOCATION)
                path= path.rpartition("/")[0]
                albums_set.add((album, path, artist))
#                print artist + " " + album

        ## manage VA albums
        li= list(albums_set)
        li.sort()
        albums_list=[] 
        current=(None, None, None)
        for triple in li:
            print triple
            if triple[1]!=current[1]:
                pair= (triple[0], triple[2])
                albums_list.append(pair)
            else:
#              print "VA candidate"+ str(current)
                if triple[1]==current[1]:
                    pair= albums_list[len(albums_list)-1]
                    albums_list[len(albums_list)-1]=(pair[0], "Various Artists")                     
            current= triple
        
#        for album in albums_list:
#            print album[0] + " " + album[1]
      
         
        self.albums= tuple(albums_list)
                
        artists_list= list(artists_set)
        artists_list.sort()
        self.artists= tuple(artists_list)

        
        print "init done: "+ str(len(self.albums)) + " albums, " + str(len(self.artists)) + " artists found"
        
    def get_artists(self):
        return self.artists
        
    def get_albums(self):
        return self.albums
        
    def get_album_playlist(self, id):
        
        pair= self.albums[int(id)]
        play_album=pair[0]
        play_artist=pair[1]
        
        print "looking for album "+ play_album + " from " + play_artist
        
        db= self.shell.props.db  
        
        res=[]
        
        li=[]
        
        self.shell.props.library_source.reset_filters()
        
        for row in self.shell.props.library_source.props.query_model:          
            if row[0].get_entry_type()==self.type_song:
                album= db.entry_get(row[0], rhythmdb.PROP_ALBUM)
                if album==play_album:
                    artist= db.entry_get(row[0], rhythmdb.PROP_ARTIST)
                    if artist==play_artist or play_artist=="Various Artists":
                        track= db.entry_get(row[0], rhythmdb.PROP_TRACK_NUMBER)
                        location= db.entry_get(row[0], rhythmdb.PROP_LOCATION)
                        li.append((track, location))
        
        li.sort()
        for t in li:
            res.append(t[1])

        return res
        
    def get_random_album_playlist(self):
		
        rnd= random.randrange(0, len(self.albums))
		
        print "random album id: "+str(rnd)
        
        return self.get_album_playlist(rnd)
